var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const fs = require('fs')
const session = require('express-session')
const RedisStore = require('connect-redis')(session)

const blogRouter = require('./routes/blog');
const userRouter = require('./routes/user')

var app = express();

const ENV = process.env.NODE_ENV
if(ENV !=='production') {
  // 开发环境|测试环境
  app.use(logger('dev', {
    stream: process.stdout
  }));
} else {
  // 正式环境
  const logFileName = path.join(__dirname, 'logs', 'access.log')
  const writeStream = fs.createWriteStream(logFileName, {
    flags: 'a'
  })
  app.use(logger('combined', {
    stream: writeStream
  }));
}

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

const redisClient = require('./db/redis')
const sessionStore = new RedisStore({
  client: redisClient
})
app.use(session({
  secret: 'WJiol_423432#',
  cookie: {
    path: '/', //默认配置
    httpOnly: true, //默认配置
    maxAge: 24*60*60*1000
  },
  store: sessionStore
}))

app.use('/api/blog', blogRouter);
app.use('/api/user', userRouter);

// 页面404处理
app.use(function(req, res, next) {
  next(createError(404));
});

// 服务端错误处理
app.use(function(err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'dev' ? err : {};
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
